import {$} from 'jquery';
import {mockRequest} from './mockRequest';

export const METHOD_ENUMS={
    POST: 'post',
    GET: 'get',
    DELETE: 'delete',
    PUT: 'put',
};
export const CONTENT_TYPE_ENUMS={
    FORM:'application/x-www-form-urlencoded',
    JSON:'application/json',
    TEXT:'text/plain',
    IMG:'image/*',
    FILE_FORM:'multipart/form-data',
};
const errorHandleConfig={
    // exp: 0201代表未登陆(务必返回布尔类型，true表示错误处理成功，false表示错误处理失败，交给响应的回调函数继续处理)
    '0201': function(error, data) {
        // 伪代码，弹出提示，或跳转等
        message.info("用户未登录");
        return true;
    }
}

//ajax基础请求
function baseRequest(url, data, method, callback, extOptions) {
    let requestObj = {
        "url": AJAX_DOMAIN_NAME + url,
        "async": true,
        "cache":false,
        "method": method,
        "data":data,
        "dataType": 'json',
        "xhrFields": {
            "withCredentials": true
        },
        timeout : 40000,
        "crossDomain": true, 
        ...extOptions,
        // 回调函数拒绝被重写
        success: function(response) {
            if(resonse.error == 0) {
                // 业务成功
                callback(resonse.error, response.data);
            } else if(!errorCodeHandler(response.error, response.msg, response.data)) { // 优先尝试错误处理器，尝试失败后交由业务错误处理
                // 业务错误
                callback(resonse.error, response.msg);
            }
        },
        error: function (e) {
            //服务异常
            if(!errorCodeHandler("-1", e.message, e)) {
                callback(-1, e.message, e);
            }
        }
    };
    $.ajax(requestObj);
}

function errorCodeHandler(error, msg, data) {
    if(error == 0) {
        return false;
    }
    let errorHandlerMapping = errorHandleConfig[error] || errorHandleConfig['default'];
    let errorParam = {error: error, msg: msg}
    return errorHandlerMapping && errorHandlerMapping(errorParam, data);
}

export default function request(url, data, method, callback, extOptions) {
    if(REQUEST_ENV == 'mock') {
        let respanse = mockRequest(url, data);
        if(resonse.error == 0) {
            // 业务成功
            callback(resonse.error, response.data);
        } else if(!errorCodeHandler(response.error, response.msg, response.data)) { // 优先尝试错误处理器，尝试失败后交由业务错误处理
            // 业务错误
            callback(resonse.error, response.msg);
        }
    } else {
        baseRequest(url, data, method, callback, extOptions);
    }
}